<template>
  <el-breadcrumb class="breadcrumb" separator="/">
    <el-breadcrumb-item v-for="(item, index) in breadcrumbList" :key="item.path">
      <span v-if="item.redirect === 'noRedirect' || index === breadcrumbList.length - 1" class="no-redirect">
        {{ item.meta.title }}
      </span>
      <a v-else @click.prevent="handleLink(item)">
        {{ item.meta.title }}
      </a>
    </el-breadcrumb-item>
  </el-breadcrumb>
</template>

<script setup>
import { computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'

const route = useRoute()
const router = useRouter()

// 生成面包屑列表
const breadcrumbList = computed(() => {
  // 过滤掉没有meta.title的路由
  let matched = route.matched.filter(item => item.meta && item.meta.title)
  // 如果首个路由不是dashboard，则添加dashboard作为首页
  const first = matched[0]
  if (first && first.path !== '/dashboard') {
    matched = [{ path: '/dashboard', meta: { title: '仪表盘' } }].concat(matched)
  }

  return matched
})

// 处理面包屑点击
const handleLink = item => {
  const { redirect, path } = item
  if (redirect) {
    router.push(redirect)
    return
  }
  router.push(path)
}
</script>

<style scoped>
.breadcrumb {
  display: inline-block;
  font-size: 14px;
  line-height: 50px;
  margin-left: 8px;
}

.no-redirect {
  color: var(--el-text-color-regular);
  cursor: text;
}

.breadcrumb a {
  color: var(--el-color-primary);
  text-decoration: none;
  cursor: pointer;
}

.breadcrumb a:hover {
  color: var(--el-color-primary-light-3);
}
</style>
